<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\SendMessage;
use App\Model\HomeUserModel;
use App\Model\HomeUserScores;
use App\Model\HomeUserMemberExp;
use App\Http\Controllers\Api\HomeUserCache;
use App\Http\Requests\HomeAddUserValidata;
use Illuminate\Support\Facades\Redis;
use App\Model\HomeUserCaptcha;
use App\Http\Controllers\Home\ShowLinksController;
use App\Http\Controllers\Api\IndexApi;

/**
 * 注册处理类
 * 2017年10月31日16:42:56
 * 黎子聪
 */
class HomeRegisterController extends Controller
{
    // 显示注册页面
    public function ShowRegisterPage()
    {
        // 站点信息类
        $type = new IndexApi;
        $index = new ShowLinksController;

        // 获取站点信息
        $sate = IndexApi::getSate();
        $linksArray = $index->index();

        return view('Home.goods-register', ['sate' => $sate, 'linksArray' => $linksArray]);
    }

    /**
     * 处理注册信息
     * @return message
     */
    public function DealWithRegister(HomeAddUserValidata $request)
    {

        $captcha = HomeUserCaptcha::where([['captchaIndex', '=', $request->phone], ['type', '=', 1]])->orderBy('validperiod', 'desc')->first();

        if (empty($captcha)) {
            return redirect()->route('home.register')->with('message', '验证码已过期');
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            return redirect()->route('home.register')->with('message', '验证码已过期 ');
        }

        // 判断是否验证成功
        if ($request->code == $captcha->captcha) {
            // 准备默认值
            $picname = '150941484559f7d7bd7092b.jpg';
            $createtime = date('Y-m-d h:i:s');
            $sex = 1;

            //添加user表信息
            $user_id = HomeUserModel::insertGetId([
                'username'   => $request->username,
                'passname'   => password_hash($request->password, PASSWORD_DEFAULT),
                'phone'      => $request->phone,
                'sex'        => $sex,
                'pic'        => $picname,
                'created_at' => $createtime,
            ]);

            // 给该用户添加对应的会员经验表
            HomeUserMemberExp::insert(
                [
                    'user_id'  => $user_id,
                ]
            );

            // 给该用户添加对应的积分表
            $result = HomeUserScores::insert(
                [
                    'user_id' => $user_id,
                    'scores'  => '0',
                ]
            );
            // 删除使用过的验证码
            HomeUserCaptcha::where([
                ['captchaIndex', '=', $request->phone],
                ['type', '=', 1],
            ])->delete();
        } else {
            return redirect()->route('home.register')->with('message', '验证码不正确');
        }

        // 判断是否注册成功
        if ($result) {
            // 获取用户信息
            $mysqluser = HomeUserModel::where('phone', $request->phone)->first();
            // 得到记录登录方法的实例
            $loginannal = new HomeUserCache;
            // 记录登录次数
            $loginnumber = $loginannal->LoginAnnal($mysqluser->id);

            $user = [
                'id'         => $mysqluser->id,
                'username'   => $mysqluser->username,
                'sex'        => $mysqluser->sex,
                'pic'        => $mysqluser->pic,
                'email'      => $mysqluser->email,
                'member'     => $mysqluser->member,
            ];

            session(['Homeuser-data' => $user]);
            return redirect()->route('home.user');
        }

        // 失败返回信息
        return redirect()->route('home.register')->with('message', '服务器繁忙，请稍后再试');

    }

    /**
     * ajax请求，判断手机号是否已注册s
     * @return 1:'该手机号已被注册'  2:'该手机号尚未注册'
     */
    public function showphone(Request $request)
    {
        // 准备redis键名
        $userkey = 'home_user_hash_phone:'.$request->phone;

        // 查询redis该手机号是否已注册
        $result = Redis::hGetAll($userkey);

        if ($result) {
            // 已注册返回
            return 1;
        }

        // 查询数据库该手机号是否已注册
        $result = HomeUserModel::select('id')->where('phone', $request->phone)->get();

        if (isset($result[0])) {
            // 已注册返回1
            return 1;
        }
        // 未注册返回2
        return 2;
    }

    /**
     * 发送手机验证码
     * data $phone $type[1:注册状态码 2:登录状态码 3:修改密码状态码]
     * @return status validperiod message code type
     */
    public function SendPhoneMessage(Request $request)
    {

      // 查询该用户的验证码
      $captcha = HomeUserCaptcha::where([
          ['captchaIndex', '=', $request->phone],
          ['type', '=', 1],
        ])
        ->orderBy('validperiod', 'desc')
        ->first();

        if ($captcha) {

            // 判断是否手贱
            if ($captcha->validperiod > time()) {
                return 403;
            }
        }

        // 获取对象
        $send = new SendMessage;

        // 调用方法发送验证码
        $result = $send->SendPhoneMessage($request->phone, 1);

        // 判断是否发送成功
        if ($result['status'] == "200") {
            // 成功时把验证信息添加到表内
            HomeUserCaptcha::insert([
                'captchaIndex'=> $request->phone,
                'captcha'     => $result['captcha'],
                'validperiod' => $result['validperiod'],
                'type'        => $result['type'],
            ]);

        }


        // 返回状态码
        return $result['status'];
    }

    /**
     * 验证短信验证码是否正确
     * @return 403['验证码过期'] 500['验证码错误'] 200['验证成功']
     */
    public function ValidataRegister(Request $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->phone],
            ['type', '=', 1],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();

        // 判断是否有该用户的验证码
        if (!$captcha) {
            return 500;
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            return 403;
        }

        // 判断是否验证成功
        if ($request->code == $captcha->captcha) {
            return 200;
        }

        return 500;
    }

}
